package com.les.ufcg.gerenciador.db;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseSqLite extends SQLiteOpenHelper {
	
	
	private static final String DATABASE_NAME = "lendmanager";
	private static final int DATABASE_VERSION = 1;
	private Context mContext;
	
	
	public DatabaseSqLite(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
	}
	
	
	public DatabaseSqLite(Context context) {
		this(context, DATABASE_NAME, null, DATABASE_VERSION);
		this.mContext = context;
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		db.beginTransaction();	
		try {
			execComandosSQL(db, ComandosSQL.getSQL());
			db.setTransactionSuccessful();
		} catch (SQLException e) {
			Log.e("Erro ao criar as tabelas do BD", e.toString());
			throw e;
		} finally {
			db.endTransaction();
		}
	}

	/**
	 * Executa os comandos SQL ao inicializar as tabelas do banco de dados
	 * @param db
	 * @param sql
	 */
	private void execComandosSQL(SQLiteDatabase db, String[] sql) {
		for (String s : sql) {
			if (s.trim().length() > 0) {
				db.execSQL(s);
			}
		}
	}


	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
	}

}